package com.ruoyi.pos.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pos.domain.dto.common.response.BasePageResponse;
import com.ruoyi.pos.domain.dto.transaction.request.SaleTicketCreateRequest;
import com.ruoyi.pos.domain.dto.transaction.request.SaleTicketQueryRequest;
import com.ruoyi.pos.domain.dto.transaction.response.SaleTicketResponse;
import com.ruoyi.pos.service.transaction.IPosSaleTicketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * POS交易小票Controller
 * 
 * @author ruoyi
 * @date 2025-01-30
 */
@Api(tags = "POS交易小票管理")
@RestController
@RequestMapping("/pos/transaction")
public class PosSaleTicketController extends BaseController {

    @Autowired
    private IPosSaleTicketService posSaleTicketService;

    /**
     * 查询交易小票列表
     */
    @ApiOperation("查询交易小票列表")
    @PreAuthorize("@ss.hasPermi('pos:transaction:list')")
    @GetMapping("/list")
    public TableDataInfo list(SaleTicketQueryRequest request) {
        startPage();
        BasePageResponse<SaleTicketResponse> response = posSaleTicketService.querySaleTickets(request);
        TableDataInfo dataTable = new TableDataInfo();
        dataTable.setCode(response.getCode());
        dataTable.setMsg(response.getMsg());
        dataTable.setRows(response.getRows());
        dataTable.setTotal(response.getTotal());
        return dataTable;
    }

    /**
     * 导出交易小票列表
     */
    @ApiOperation("导出交易小票列表")
    @PreAuthorize("@ss.hasPermi('pos:transaction:export')")
    @Log(title = "POS交易小票", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SaleTicketQueryRequest request) {
        BasePageResponse<SaleTicketResponse> pageResponse = posSaleTicketService.querySaleTickets(request);
        ExcelUtil<SaleTicketResponse> util = new ExcelUtil<SaleTicketResponse>(SaleTicketResponse.class);
        util.exportExcel(response, pageResponse.getRows(), "交易小票数据");
    }

    /**
     * 获取交易小票详细信息（按ID）
     */
    @ApiOperation("获取交易小票详细信息")
    @PreAuthorize("@ss.hasPermi('pos:transaction:query')")
    @GetMapping(value = "/{transactionId}")
    public AjaxResult getInfo(@ApiParam("交易ID") @PathVariable Long transactionId) {
        return success(posSaleTicketService.getSaleTicketById(transactionId));
    }

    /**
     * 根据流水号查询小票
     */
    @ApiOperation("根据流水号查询小票")
    @PreAuthorize("@ss.hasPermi('pos:transaction:query')")
    @GetMapping(value = "/no/{transactionNo}")
    public AjaxResult getByNo(@ApiParam("交易流水号") @PathVariable String transactionNo) {
        return success(posSaleTicketService.getSaleTicketByNo(transactionNo));
    }

    /**
     * 查询小票明细
     */
    @ApiOperation("查询小票明细")
    @PreAuthorize("@ss.hasPermi('pos:transaction:query')")
    @GetMapping("/details/{transactionId}")
    public AjaxResult getDetails(@ApiParam("交易ID") @PathVariable Long transactionId) {
        try {
            SaleTicketResponse response = posSaleTicketService.getSaleTicketById(transactionId);
            if (response != null && response.getSuccess()) {
                return success(response.getSaleDetails());
            } else {
                return error("查询小票明细失败");
            }
        } catch (Exception e) {
            return error("查询小票明细失败：" + e.getMessage());
        }
    }

    /**
     * 查询小票支付信息
     */
    @ApiOperation("查询小票支付信息")
    @PreAuthorize("@ss.hasPermi('pos:transaction:query')")
    @GetMapping("/pays/{transactionId}")
    public AjaxResult getPays(@ApiParam("交易ID") @PathVariable Long transactionId) {
        try {
            SaleTicketResponse response = posSaleTicketService.getSaleTicketById(transactionId);
            if (response != null && response.getSuccess()) {
                // TODO: SaleTicketResponse需要添加getPayInfos()方法
                return success(new ArrayList<>());
            } else {
                return error("查询支付信息失败");
            }
        } catch (Exception e) {
            return error("查询支付信息失败：" + e.getMessage());
        }
    }

    /**
     * 创建销售小票（移动POS端使用）
     */
    @ApiOperation("创建销售小票")
    @PreAuthorize("@ss.hasPermi('pos:transaction:add')")
    @Log(title = "POS交易小票", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody SaleTicketCreateRequest request) {
        try {
            SaleTicketResponse response = posSaleTicketService.createSaleTicket(request);
            if (response.getSuccess()) {
                return success(response);
            } else {
                return error(response.getMessage());
            }
        } catch (Exception e) {
            return error("创建销售小票失败：" + e.getMessage());
        }
    }

    /**
     * 取消销售小票
     */
    @ApiOperation("取消销售小票")
    @PreAuthorize("@ss.hasPermi('pos:transaction:cancel')")
    @Log(title = "取消销售小票", businessType = BusinessType.UPDATE)
    @PutMapping("/cancel/{transactionId}")
    public AjaxResult cancel(@ApiParam("交易ID") @PathVariable Long transactionId, 
                            @RequestParam String reason) {
        try {
            boolean result = posSaleTicketService.cancelSaleTicket(transactionId, reason);
            return toAjax(result ? 1 : 0);
        } catch (Exception e) {
            return error("取消销售小票失败：" + e.getMessage());
        }
    }

    /**
     * 验证小票（管理员校验功能）
     */
    @ApiOperation("验证小票")
    @PreAuthorize("@ss.hasPermi('pos:transaction:validate')")
    @PostMapping("/validate")
    public AjaxResult validate(@RequestBody Map<String, Object> params) {
        try {
            Long transactionId = Long.valueOf(params.get("transactionId").toString());
            Long cashierId = Long.valueOf(params.get("cashierId").toString());
            
            boolean result = posSaleTicketService.validateRefundPermission(transactionId, cashierId);
            if (result) {
                return success("验证通过");
            } else {
                return error("验证失败：无退货权限");
            }
        } catch (Exception e) {
            return error("验证失败：" + e.getMessage());
        }
    }

    /**
     * 查询退货记录
     */
    @ApiOperation("查询退货记录")
    @PreAuthorize("@ss.hasPermi('pos:transaction:refund')")
    @GetMapping("/refunds")
    public AjaxResult getRefunds(SaleTicketQueryRequest request) {
        try {
            // TODO: IPosSaleTicketService.getRefundRecords参数需要修改
            return success(new ArrayList<>());
        } catch (Exception e) {
            return error("查询退货记录失败：" + e.getMessage());
        }
    }

    /**
     * 查询收银员退货记录
     */
    @ApiOperation("查询收银员退货记录")
    @PreAuthorize("@ss.hasPermi('pos:transaction:refund')")
    @GetMapping("/refunds/cashier/{cashierId}")
    public AjaxResult getCashierRefunds(@ApiParam("收银员ID") @PathVariable Long cashierId,
                                       @RequestParam String startTime,
                                       @RequestParam String endTime) {
        try {
            List<SaleTicketResponse> refunds = posSaleTicketService.getCashierRefundRecords(
                cashierId, 
                startTime, 
                endTime
            );
            return success(refunds);
        } catch (Exception e) {
            return error("查询收银员退货记录失败：" + e.getMessage());
        }
    }

    /**
     * 处理退货
     */
    @ApiOperation("处理退货")
    @PreAuthorize("@ss.hasPermi('pos:transaction:refund')")
    @Log(title = "POS退货", businessType = BusinessType.INSERT)
    @PostMapping("/refund")
    public AjaxResult refund(@Valid @RequestBody SaleTicketCreateRequest request) {
        try {
            // 退货也使用创建销售小票的接口，但交易类型为退货
            SaleTicketResponse response = posSaleTicketService.createSaleTicket(request);
            if (response.getSuccess()) {
                return success(response);
            } else {
                return error(response.getMessage());
            }
        } catch (Exception e) {
            return error("处理退货失败：" + e.getMessage());
        }
    }
}
